# Create your views here.
#!/usr/bin/env python
# coding=utf-8
import json

from django.shortcuts import render
import pymysql
from urllib3 import request
import uuid
from .forms import UserProfileForm
from django.views.decorators.http import require_POST
from django.contrib.auth.models import User
from matrix.mytools.demo_data import company, status
from serverworker.funqrcode.qr_lable import create_lable

from django.db import IntegrityError
import io
import matrix.confs.conf_network as conf
from urllib.parse import quote #将中文进行URL 编码
from django.http import HttpResponse
from django.forms.models import model_to_dict
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.views.decorators.http import require_http_methods
from serverworker  import models
from django.core import serializers
from django.contrib.auth.models import User

conn = pymysql.connect(
    host='172.10.10.6',
    port=3306,
    user='root',
    passwd='Test@123',
    db = 'test'

    )

dtype = {
    0: u'未知分类',
    1: u'无法播放',
    2: u'违规举报',
    3: u'质量问题',
}

dstatus = {
    0: u'待确认',
    1: u'待解决',
    2: u'已解决',
    3: u'无需解决',
}

def feedback_stats(request):
    cursor = conn.cursor()
    cursor.execute('select defect_type, status, count(1) as cnt, left(ctime, 10) from feedback group by defect_type, status, left(ctime, 10)  ;')
    records = [(dtype[x[0]], dstatus[x[1]], x[2], x[3]) for x in cursor.fetchall()]
    theads = ['反馈类型', '当前状态', '数量', '时间']
    return render(request, 'de.html', {"theads": theads, "trows": records})

def a():
    cursor = conn.cursor()
    cursor.execute('select defect_type, status, count(1) as cnt, left(ctime, 10) from feedback group by defect_type, status, left(ctime, 10) ;')
    #print(cursor.fetchall())
    records = [(dtype[x[0]], dstatus[x[1]], x[2], x[3]) for x in cursor.fetchall()]
    print(records)

def helloword(request):
    return render(request,'demo/hello.html')


def demo_table(request):
    list_head=['反馈类型', '当前状态', '数量', '时间']
    data = [[1,2,3,4],[1,2,3,4]]
    return render(request,'demo/table.html',{'list_head':list_head,'data':data})

def qr(request):
    print('request.GET data: ',request.GET)
    device_id = request.GET.get('device_id')
    device_name = request.GET['device_name']
    group = request.GET['scene']+'-'+request.GET['project']+'-'+request.GET['device_class']
    func =request.GET['func']

    #print(device_id,device_name,group,func)

    image_data = create_lable(700,170,device_id,device_name,group,func)
        #'9dcfa6220516074c',"门禁服务器11",'归属:太平洋保险金融大厦-门禁系统','功能:门禁系统管理、通信'

    img_io = io.BytesIO()
    image_data.save(img_io, 'PNG')
    response = HttpResponse(content_type='image/png')
    image_data.save(response, 'PNG')

    return response
    image_data.seek(0)


def qr_download(request):
    print('request.GET data: ',request.GET)
    device_id = request.GET.get('device_id')
    device_name = request.GET['device_name']
    group = request.GET['scene']+'-'+request.GET['project']+'-'+request.GET['device_class']
    func =request.GET['func']

    #print(device_id,device_name,group,func)
    a='aaa'
    image_data = create_lable(700,170,device_id,device_name,group,func)
        #'9dcfa6220516074c',"门禁服务器11",'归属:太平洋保险金融大厦-门禁系统','功能:门禁系统管理、通信'

    img_io = io.BytesIO()
    image_data.save(img_io, 'PNG')
    response = HttpResponse(content_type='application/octet-stream') #实现只下载、不打开
    print(device_name)
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(quote(device_name+'_'+device_id+'.png'))
    image_data.save(response, 'PNG')

    return response
    image_data.seek(0)
def not_qr2(request):
    with open('C:/Users/STATION/Pictures/rss1.png', 'rb') as image_file:
        image_content = image_file.read()
    # 创建HttpResponse对象，设置MIME类型为图片
    response = HttpResponse(image_content, content_type='image/png')

    # 设置弹窗的样式，使图片在载入时即弹出
    response['Content-Disposition'] = 'inline; filename="image.png"'

    return response

def my_custom_view(request, id):
    # 处理请求，返回响应
    return HttpResponse("自定义视图内容")

############################################################w微信小程序

#登录
def wechat_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print(username,password)
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return render(request, 'demo/login_access.html')  # Redirect to a success page.
            print('login access')
        else:
            return render(request, 'mylogin.html', {'error': 'Invalid login credentials.登录失败'})
    return render(request, 'mylogin.html')

#@login_required
def demo(request):
    #print(request.headers['Cookie'])
    #return HttpResponse("自定义视图内容")
    return render(request, 'myupload.html', )


########################### img


#test not
def testq(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('hello.html')  # 替换为实际的成功跳转 URL
    else:
        form = UserProfileForm()
    return render(request, 'myupload.html', {'form': form})

########################### 微信扫码查询
def select_device_info_one(request):
    print('star')
    device_id = request.GET['device_id']
    lis_key = ['公司','现场','项目','类型','名称','编号','管理员','技术员','操作员','创建人','功能','创建时间']
    data = models.Device_info.objects.filter(device_id=device_id)
    data = data[0]
    n = {lis_key[0]: data.company.company,
         lis_key[1]: data.scene.scene,
         lis_key[2]: data.project.project,
         lis_key[3]: data.device_class.device_class,
         lis_key[4]: data.device_name,
         lis_key[5]: data.device_id,
         lis_key[6]: data.admin_user.username,
         lis_key[7]: data.teach_user.username,
         lis_key[8]: data.watch_user.username,
         lis_key[9]: data.create_user.username,
         lis_key[10]: data.func,
         lis_key[11]: data.create_time,
         'photo':conf.url+'static'+data.photo.url
         }  #
    print(n)
    return HttpResponse(JsonResponse(n)) # JsonResponse处理图片报错错

def select_device_attribute_one(request):
    device_id = request.GET['device_id']
    lis_all = []

    photo = models.Device_info.objects.filter(device_id=device_id)[0].photo.url
    data = models.Device_attribute.objects.filter(device_name=device_id,status=1)

    data_head = data.filter(is_head=1)[0]
    lis_head = ['名称', data_head.a1, data_head.b1, data_head.c1, data_head.d1, data_head.e1, data_head.f1,
                data_head.g1, data_head.h1, data_head.notes, '创建人', '创建时间']
    data = data.filter(is_head=0)
    lis_all.append(lis_head)
    for i in data:
        lis_all.append([i.device_name.device_name, i.a1, i.b1, i.c1, i.d1, i.e1, i.f1, i.g1, i.h1, i.notes,i.create_user.username, i.create_time])
    print(lis_all)
    return HttpResponse(JsonResponse(lis_all, safe=False))

def select_device_maintenance_log_one(request):
    device_id = request.GET['device_id']
    lis_all = []


    photo = models.Device_info.objects.filter(device_id=device_id)[0].photo.url
    data = models.Device_maintenance_log.objects.filter(device_name=device_id).all()
    lis_all.append([data[0].device_name.__str__()])
    for i in data:
        # i.photo1, i.photo2, i.photo3,  '照片','照片','照片',
        lis_i = [i.plan,i.problem, i.solution,  i.replace, i.notes,i.maintenance_user.username,
                  i.create_time]
        lis_all.append(lis_i)
        print(lis_i)
    print(lis_all)

    return HttpResponse(JsonResponse(lis_all, safe=False))

def get_organ_index(request):
    lis_com = []
    lis_sce = []
    lis_pro = []
    lis_cla = []
    lis_use = []
    lis_all  =[]
    com = models.organ_index_company.objects.filter(status=1).all()
    for i in com:
       lis_com.append(i.company)
    sce = models.organ_index_scene.objects.filter(status=1).all()
    for i in sce:
       lis_sce.append(i.scene )
    pro = models.organ_index_project.objects.filter(status=1).all()
    for i in pro:
       lis_pro.append(i.project )
    cla = models.organ_index_class.objects.filter(status=1).all()
    for i in cla:
       lis_cla.append(i.device_class )
    usr = User.objects.all()
    for i in usr:
        lis_use.append(i.username)


    lis_all = [lis_com,lis_sce,lis_pro,lis_cla,lis_use]
    print(lis_all)
    return HttpResponse(JsonResponse(lis_all, safe=False))

def add_device_info_one(request):
    print(request.POST)
    print(request.POST.get('lis'))
    data = json.loads(request.POST.get('lis'))
    print(request.FILES['fimg'])
    if '-' in data:
        print("数据未填完整，请检查是否有空白")
        return HttpResponse("数据未填完整，请检查是否有空白")
    try:
        instance = models.Device_info.objects.create(
                                      company=models.organ_index_company.objects.get(company=data[0]),
                                      scene=models.organ_index_scene.objects.get(scene=data[1]),
                                      project=models.organ_index_project.objects.get(project=data[2]),
                                      device_class=models.organ_index_class.objects.get(device_class=data[3]),
                                      create_user=User.objects.get(username=data[4]), #User.objects.get(username=request.user),
                                      admin_user=User.objects.get(username=data[4]),
                                      teach_user=User.objects.get(username=data[5]),
                                      watch_user=User.objects.get(username=data[6]),
                                      device_name=data[7],
                                      funcz=data[8],
                                      photo=request.FILES['fimg'],
                                      device_id=uuid.uuid4().hex[16:])
        # 创建成功
        print('创建成功，新对象ID：', instance,instance.id)
    except IntegrityError as e:
        print('创建失败：', e)
        return HttpResponse(e)
    except Exception as e:
        # 其他异常
        print('创建时发生未知错误：', e)
        return HttpResponse(e)
    return HttpResponse("保存成功")

def add_device_attribute_one(request):
    device_id = request.GET['device_id']
    lis_head = []

    res = models.Device_attribute.objects.filter(device_name=device_id, status=1, is_head=1).all()[0]
    lis_head = [res.a1, res.b1, res.c1, res.d1, res.e1, res.f1, res.g1, res.h1, res.notes, res.create_time,res.order_id]

    data=[]
    if '-' in data:
        print("数据未填完整，请检查是否有空白")
        return HttpResponse("数据未填完整，请检查是否有空白")
    try:
        instance = models.Device_info.objects.create(
                                      company=models.organ_index_company.objects.get(company=data[0]),
                                      scene=models.organ_index_scene.objects.get(scene=data[1]),
                                      project=models.organ_index_project.objects.get(project=data[2]),
                                      device_class=models.organ_index_class.objects.get(device_class=data[3]),
                                      create_user=User.objects.get(username=data[4]), #User.objects.get(username=request.user),
                                      admin_user=User.objects.get(username=data[4]),
                                      teach_user=User.objects.get(username=data[5]),
                                      watch_user=User.objects.get(username=data[6]),
                                      device_name=data[7],
                                      funcz=data[8],
                                      photo=request.FILES['fimg'],
                                      device_id=uuid.uuid4().hex[16:])
        # 创建成功
        print('创建成功，新对象ID：', instance,instance.id)
    except IntegrityError as e:
        print('创建失败：', e)
        return HttpResponse(e)
    except Exception as e:
        # 其他异常
        print('创建时发生未知错误：', e)
        return HttpResponse(e)
    return HttpResponse("保存成功")



from django.shortcuts import render

def echarts(request):
    return render(request,'demo.html')
from pyecharts.charts import Bar

def e2(request):
    bar = Bar()
    bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
    # render 会生成本地 HTML 文件，默认会在当前目录生成 render.html 文件
    # 也可以传入路径参数，如 bar.render("mycharts.html")
    bar.render()





if __name__ == '__main__':
    print('views')
    e2(request)
